package com.atguigu.gmallauth.service;

import com.atguigu.gmall.common.bean.ResponseVo;
import com.atguigu.gmall.common.exception.AuthException;
import com.atguigu.gmall.common.utils.CookieUtils;
import com.atguigu.gmall.common.utils.IpUtils;
import com.atguigu.gmall.common.utils.JwtUtils;
import com.atguigu.gmall.ums.entity.UserEntity;
import com.atguigu.gmallauth.config.JwtProperties;
import com.atguigu.gmallauth.feign.GmallUmsClient;
import org.bouncycastle.math.raw.Mod;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.EnableAutoConfiguration;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.stereotype.Service;
import org.springframework.web.bind.annotation.CookieValue;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.HashMap;
import java.util.Map;

/**
 * @author Jia Fa
 * @create 2021-12-17 12:54
 */
@Service
@EnableConfigurationProperties(JwtProperties.class)
public class AuthService {

    @Autowired
    GmallUmsClient umsClient;
    @Autowired
    JwtProperties jwtProperties; // 注入配置信息

    public void login(String loginName, String password, HttpServletRequest request, HttpServletResponse response) {
        try {
            // 远程访问ums 查询该用户信息是否存在
            ResponseVo<UserEntity> userEntityResponseVo = this.umsClient.queryUser(loginName, password);
            UserEntity userEntity = userEntityResponseVo.getData();
            // 判空
            if (userEntity == null) {
                //用户名密码不正确，不能获取用户，登录失败
                 throw new AuthException("用户名密码不正确");
            }
            // 放入用户名信息到载荷
            Map<String,Object> map = new HashMap<>();
            map.put("userId", userEntity.getId());
            map.put("username",userEntity.getUsername());

            // 为防止盗链 将用户ip信息放入载荷
            String ip = IpUtils.getIpAddressAtService(request);
            map.put("ip", ip);

            // 制作token(jwt)
            String token = JwtUtils.generateToken(map, jwtProperties.getPrivateKey(), jwtProperties.getExpire());

            // 设置token到cookie
            // request, response cookieName token 过期时间s
            CookieUtils.setCookie(request, response, jwtProperties.getCookieName(), token, jwtProperties.getExpire()*60);
            // 为了方便页面展示登录用户昵称，向cookie中单独写入昵称  unick
            CookieUtils.setCookie(request,response,jwtProperties.getUnick(),userEntity.getNickname(),jwtProperties.getExpire()*60);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}
